<?php
namespace app\common\logic;
use app\common\model\Wechats;
use app\common\model\Materials;
use app\common\model\Attachment;
class Wechat
{
    /*自定义生成菜单*/
    public function createMenu($wechat_id=0){
       $token = Wechats::where(['id'=>$wechat_id])->value('token');
       $weObj = $this->weObj($wechat_id);
       $data = '{"button":[';
       $class = db('wx_menu')->where(array("pid" => 0,'wechat_id'=>$wechat_id))->limit(3)->order('sort asc,menu_id asc')->select();
       $kcount = db('wx_menu')->where(array("pid" => 0,'wechat_id'=>$wechat_id))->count();
       // 删除所有的菜单
       if(intval($kcount) == 0){
            return $res = $weObj->deleteMenu();
       }
       $k = 1;
       foreach ($class as $key => $vo) {
            //主菜单
            $data .= '{"name":"' . $vo['menu_name'] . '",';
            $c = db('wx_menu')->where(array("pid" => $vo['menu_id'],'wechat_id'=>$wechat_id))->limit(5)->order('sort asc,menu_id asc')->select();
            if(!$c || $c == null || $c == ''){
                if($vo['menu_event_type'] == ''){ 
                    return ['code'=>-1,'errmsg'=>'一级菜单【'.$vo['menu_name'].'】的事件类型没有选择'];
                }
                //if($vo['key'] == ''){ $this->error(L('一级菜单').$vo['title'].L('的Key/Url没有设置')); exit; }
            }
            $count = db('wx_menu')->where(array("pid" => $vo['menu_id'],'wechat_id'=>$wechat_id))->count();
            //子菜单
            if (!empty($c)) {
                $data .= '"sub_button":[';
            } else {
                if (in_array($vo['menu_event_type'], array('1'))) {
                    $data .= '"type":"view","title":"' . $vo['menu_name'] . '","url":"' . createUrl($vo['menu_event_url'], $token) . '"';
                }else if($vo['menu_event_type'] == 2){
                    $data .= '"type":"click","title":"' . $vo['menu_name'] . '","key":"' . $vo['menu_id'] . '"';
                }else if($vo['menu_event_type'] == 3){ // 小程序
                    $opt = json_decode($vo['options'],true);
                    $data .= '"type":"miniprogram","title":"' . $vo['menu_name'] . '","appid":"' . $opt['appid'] . '","pagepath":"'.$opt['path'].'","url":"'.$opt['url'].'"';
                }   
                else{
                    $data .= '"type":"'.$vo['menu_event_type'].'","title":"' . $vo['menu_name'] . '","key":"' . $vo['menu_event_url'] . '"';
                }
            }
            $i = 1;
            foreach ($c as $voo) {
                if($voo['menu_event_type'] == ''){ 
                    //$this->error(lang('二级菜单').$voo['menu_name'].lang('的事件类型没有选择')); 
                    return ['code'=>-1,'errmsg'=>'二级菜单【'.$voo['menu_name'].'】的事件类型没有选择'];
                }
                //if($voo['key'] == ''){ $this->error(L('二级菜单').$voo['title'].L('的Key/Url没有设置')); exit; }
                if ($i == $count) {
                    if (in_array($voo['menu_event_type'], array(1))) {
                        $data .= '{"type":"view","name":"' . $voo['menu_name'] . '","url":"' . createUrl($voo['menu_event_url'], $token) . '"}';
                    } else if($voo['menu_event_type'] == 2){
                        $data .= '{"type":"click","name":"' . $voo['menu_name'] . '","key":"'.$voo['menu_id'].'"}';
                    }else if($vo['menu_event_type'] == 3){ // 小程序
                        $opt = json_decode($voo['options'],true);
                        $data .= '{"type":"miniprogram","title":"' . $vo['menu_name'] . '","appid":"' . $opt['appid'] . '","pagepath":"'.$opt['path'].'","url":"'.$opt['url'].'"}';
                    }else {
                        $data .= '{"type":"'.$voo['menu_event_type'].'","name":"' . $voo['menu_name'] . '","key":"'.$voo['menu_event_url'].'"}';
                    }
                } else {
                    if (in_array($voo['menu_event_type'], array(1))) {
                        $data .= '{"type":"view","name":"' . $voo['menu_name'] . '","url":"' . createUrl($voo['menu_event_url'], $token) . '"},';
                    }else if($voo['menu_event_type'] == 2){
                        $data .= '{"type":"click","name":"' . $voo['menu_name'] . '","key":"'.$voo['menu_id'].'"},';
                    }else if($vo['menu_event_type'] == 3){ // 小程序
                        $opt = json_decode($voo['options'],true);
                        $data .= '{"type":"miniprogram","title":"' . $vo['menu_name'] . '","appid":"' . $opt['appid'] . '","pagepath":"'.$opt['path'].'","url":"'.$opt['url'].'"},';
                    }else {
                        $data .= '{"type":"'.$voo['menu_event_type'].'","name":"' . $voo['menu_name'] . '","key":"'.$voo['menu_event_url'].'"},';
                    }
                }
                $i++;
            }
            if ($c != false) {
                $data .= ']';
            }
            if ($k == $kcount) {
                $data .= '}';
            } else {
                $data .= '},';
            }
            $k++;
        }
        $data .= ']}';
        $data = json_decode($data,true);
        $res = $weObj->createMenu($data);
        return $res;
    }

     public function weObj($wechat_id){
        $options =(new \app\common\model\Wechats)->getById($wechat_id);
        $Token_Access = (new \app\common\model\Wechats)->Token_Access($options);
        return $weobj = WX($options,$Token_Access);
    }
    // 上传图文
    public function uploadmpnews($id,$wechat_id,$fasg=false){
        $media_id = db('material_wechat')->where('news_id',$id)->where('wechat_id',$wechat_id)->value('media_id');
        if(!empty($media_id)){
            return $media_id;
        }
        $row = Materials::where('id',$id)->find();
        if(empty($row)){
            return ['code'=>-1,'errmsg'=>'图文信息不存在'];
        }
        $row = $row->toArray();
        
        $items = (new Materials)->getMaterialItems($row['id']);
        $items = is_array($items) ? $items : [];
        $items = array_merge([$row],$items);
        $articles = $newsIds = [];
        foreach($items as $item){
            $thumb_media_id = null;
            if(!empty($item['thumb'])){
                $thumb_media_id = (new Attachment)->getMedia_id($item['thumb'],$wechat_id);
            }
            $show_cover_pic = 1;
            if(empty($thumb_media_id)){
                $show_cover_pic = 0;
            }
            $articles[] = array(
                'title' => $item['title'],
                'author' => $item['author'],
                'thumb_media_id' => $thumb_media_id,
                'show_cover_pic' => $show_cover_pic,
                'digest' => $item['digest'],
                'content' => getContentFmt($item['content'],$wechat_id),
                'content_source_url' => $item['content_source_url'],
                'need_open_comment' => (int)$item['need_open_comment'],
                'only_fans_can_comment' => (int)$item['only_fans_can_comment'],
            );
            $newsIds[] = ['wechat_id' => $wechat_id,'news_id' => $item['id'],'media_id'=>''];
        }
        $result = $this->weObj($wechat_id)->createMaterials(['articles'=>$articles]);
        if($result !== true){
            return $result;
        }
        $newsIds[0]['media_id'] = $result['media_id'];
        db('material_wechat')->insertAll($newsIds,true);
        return $result['media_id'];
    }
}